//
//  BaseDataModel.m
//  ShowTimeApp
//
//  Created by Ruby on 10/24/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "BaseDataModel.h"
#define STOREPATH [NSHomeDirectory() stringByAppendingString:@"/Documents/db1.sqlite"]


@implementation BaseDataModel
@synthesize managedObjectContext;
@synthesize managedObjectModel;
@synthesize persistentStoreCoordinator;
@synthesize fetchResultController;

//Constructor
-(id)initBaseDataModel{
    [self init];
    [self initCoreData];
    return self;
}

//Khoi tao context, model, coordinator
-(void)initCoreData{
    NSError *error;
	NSURL *url = [NSURL fileURLWithPath:STOREPATH];
	
	// Init the model, coordinator, context
	NSManagedObjectModel *mObjectModel  = [NSManagedObjectModel mergedModelFromBundles:nil];
	NSPersistentStoreCoordinator *pStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mObjectModel];
	if (![pStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error]) 
		NSLog(@"Error: %@", [error localizedDescription]);
	else
	{
		self.managedObjectContext = [[[NSManagedObjectContext alloc] init] autorelease];
		[self.managedObjectContext setPersistentStoreCoordinator:pStoreCoordinator];
    }
	[pStoreCoordinator release];
}

//Lay toan bo ds object theo entityName, sap xep 
//data tra ve luu vao fetchResultController.fetchedObjects
-(void)fetchObjects:(NSString *)entityName sortBy:(NSSortDescriptor *)sortDescriptor{
    
    // Init fetch request
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    [fetchRequest setEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:self.managedObjectContext]];
    
    // Add a sort descriptor
	NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor];
	[fetchRequest setSortDescriptors:descriptors];
	[sortDescriptor release];    
    
	// Init the fetched results controller
	NSError *error;
    self.fetchResultController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
	if (![self.fetchResultController performFetch:&error])	
        NSLog(@"Error: %@", [error localizedDescription]);
    
	[self.fetchResultController release];
	[fetchRequest release];
}

//Lay toan bo ds object theo entityName, sap xep, xet dieu kien 
//data tra ve luu vao fetchResultController.fetchedObjects
-(void)fetchObjects:(NSString *)entityName sortBy:(NSSortDescriptor *)sortDescriptor byPredicate:(NSPredicate *)predicate{
    
    // Init fetch request
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    [fetchRequest setEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:self.managedObjectContext]];
    
    // Add a sort descriptor
	NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor];
	[fetchRequest setSortDescriptors:descriptors];
	[sortDescriptor release];
    
    // Init predicate for fetch
    fetchRequest.predicate = predicate;
    
	// Init the fetched results controller
	NSError *error;
    self.fetchResultController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
	if (![self.fetchResultController performFetch:&error])	
        NSLog(@"Error: %@", [error localizedDescription]);
    
	[self.fetchResultController release];
	[fetchRequest release];
}

-(NSManagedObject*) fetchObject:(NSString *)entityName byPredicate:(NSPredicate *)predicate{

    NSManagedObject* result=nil;
    // Init fetch request
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    [fetchRequest setEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:self.managedObjectContext]];
    [fetchRequest setPredicate:predicate];
        
    // Add a sort descriptor
	NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"ID" ascending:NO selector:nil];
    // Add a sort descriptor
	NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor];
	[fetchRequest setSortDescriptors:descriptors];
	[sortDescriptor release];
    
    // Init predicate for fetch
    fetchRequest.predicate = predicate;
    
	// Init the fetched results controller
	NSError *error;
    self.fetchResultController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
	if (![self.fetchResultController performFetch:&error])	
        NSLog(@"Error: %@", [error localizedDescription]);
    result = [self.fetchResultController.fetchedObjects lastObject];
	[self.fetchResultController release];
	[fetchRequest release];

//  NSError *error;
//  Execute fetch request
//    result= [[self.managedObjectContext executeFetchRequest:fetchRequest error:&error] lastObject];
//    if(result)
//        NSLog(@"Error: %@", [error localizedDescription]);
    
    return result;
}

//Xoa toan bo object 
-(void)removeObjects{
    NSError *error = nil;
    if(self.fetchResultController.fetchedObjects.count==0){
        NSLog(@"Nothing for deleting");
        return;
    }
    else
    {
        for(NSManagedObject *object in self.fetchResultController.fetchedObjects)
        {
            NSLog(@"Deleting");
            [self.managedObjectContext deleteObject:object];
        }
    }  
    if (![self.managedObjectContext save:&error]) 
        NSLog(@"Error: %@", [error localizedDescription]);
}

//Luu thay doi xuong file sqlite
-(BOOL)saveContent:(NSError *)error{
    error = nil;
    NSManagedObjectContext *objectContext = self.managedObjectContext;
    if (objectContext != nil)
    {
        if ([objectContext hasChanges] && ![objectContext save:&error])
        {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            return NO;
            //abort();
        }else
            return YES;
    }
    return YES;
}

/**
 Returns the URL to the application's Documents directory.
 */
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
@end
